﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace 每日时间作息
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public const string URL = "https://gitee.com/gitee-chao/daily-work-and-rest";
        DispatcherTimer workingTimer = new DispatcherTimer();
        public DispatcherTimer dispatcherTimer = new DispatcherTimer();

        public bool Shutdown = false;
        System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();

        public MainWindow()
        {
            InitializeComponent();
            TextBlock.Text = $"00:{Properties.Settings.Default.HintInterval.ToString().PadLeft(2, '0')}:00";

            //TextBlock.Text = $"00:00:02";

            this.Visibility = Visibility.Hidden;

            this.Left = SystemParameters.WorkArea.Width - this.Width;
            this.Top = SystemParameters.WorkArea.Height - this.Height;

            //提示的倒计时
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Tick += new EventHandler(CountDown);

            //工作的倒计时
            workingTimer.Interval = TimeSpan.FromSeconds(Properties.Settings.Default.WorkingInterval * 60);
            //workingTimer.Interval = TimeSpan.FromSeconds(10);
            workingTimer.Tick += new EventHandler(StartToRest);
            workingTimer.Start();





            #region "最小化"
            //最小化

            Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/icon_32.ico")).Stream;
            notifyIcon.Icon = new System.Drawing.Icon(iconStream);
            notifyIcon.Visible = false;
            notifyIcon.Text = "每日时间作息";
            notifyIcon.BalloonTipText = "每日时间作息";
            notifyIcon.ShowBalloonTip(500);
            notifyIcon.MouseDown +=
                delegate (object sender, System.Windows.Forms.MouseEventArgs args)
                {
                    if (args.Button == System.Windows.Forms.MouseButtons.Left) { ShowSetup(); }
                };
            notifyIcon.Visible = true;
            System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
            System.Windows.Forms.MenuItem menuItem1 = new System.Windows.Forms.MenuItem() { Text = "设置" };
            menuItem1.Click += (s, e) =>
            {
                ShowSetup();
            };
            System.Windows.Forms.MenuItem menuItem2 = new System.Windows.Forms.MenuItem() { Text = "关于每日作息" };
            menuItem2.Click += (s, e) =>
            {
                System.Diagnostics.Process.Start(URL);
            };


            contextMenu.MenuItems.Add(menuItem1);
            contextMenu.MenuItems.Add(menuItem2);
            notifyIcon.ContextMenu = contextMenu;
            #endregion



        }


        private void ShowSetup()
        {
            Window_Setttings window_Setttings = 每日时间作息.GetWindow.Get("Window_Setttings") as Window_Setttings;
            if (window_Setttings == null) window_Setttings = new Window_Setttings();
            window_Setttings.Show();


        }







        public string GetTime()
        {
            int h1 = int.Parse(Properties.Settings.Default.LongLockStartTime.Split(':').First());
            int m1 = int.Parse(Properties.Settings.Default.LongLockStartTime.Split(':').Last());

            int h2 = int.Parse(Properties.Settings.Default.LongLockEndTime.Split(':').First());
            int m2 = int.Parse(Properties.Settings.Default.LongLockEndTime.Split(':').Last());

            return $" {(h2 - h1).ToString().PadLeft(2, '0')}:{(m2 - m1).ToString().PadLeft(2, '0')}:00";
        }

        public void StartLongLockScreen()
        {

            Console.WriteLine("开始长时间锁屏");
            Task.Delay(1500).Wait();

            //开始长时间
            Window_LockScreen window_LockScreen = new Window_LockScreen();
            window_LockScreen.TextBlock.Text = GetTime();
            window_LockScreen.Show();


        }

        public void ShutDown()
        {
            if (Shutdown) return;
            Console.WriteLine("准备关机");
            //倒计时
            Shutdown = true;

            TextBlock.Text = $"00:{Properties.Settings.Default.HintInterval.ToString().PadLeft(2, '0')}:00";
            //TextBlock.Text = $"00:00:02";
            MsgTextBlock.Text = "关机倒计时";
            this.Show();
            FadeIn();
            dispatcherTimer.Start();
        }

        protected bool getTimeSpan(string nowTime)
        {
            //判断当前时间是否在工作时间段内
            string time1 = Properties.Settings.Default.LongLockStartTime;
            string time2 = Properties.Settings.Default.LongLockEndTime;
            TimeSpan dspWorkingDayAM = DateTime.Parse(time1).TimeOfDay;
            TimeSpan dspWorkingDayPM = DateTime.Parse(time2).TimeOfDay;
            DateTime t1 = Convert.ToDateTime(nowTime);

            TimeSpan dspNow = t1.TimeOfDay;
            if (dspNow > dspWorkingDayAM && dspNow < dspWorkingDayPM)
            {
                return true;
            }
            return false;
        }


        public void ListenTime(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            TimeSpan nowTime = new TimeSpan(now.Hour, now.Minute, 0);

            int startHour = int.Parse(Properties.Settings.Default.LongLockStartTime.Split(':').First());
            int startMinute = int.Parse(Properties.Settings.Default.LongLockStartTime.Split(':').Last());

            TimeSpan startTime = new TimeSpan(startHour, startMinute, 0);

            int endHour = int.Parse(Properties.Settings.Default.LongLockEndTime.Split(':').First());
            int endMinute = int.Parse(Properties.Settings.Default.LongLockEndTime.Split(':').Last());

            TimeSpan endTime = new TimeSpan(endHour, endMinute, 0);





            int shutdownHour = int.Parse(Properties.Settings.Default.ShutDownTime.Split(':').First());
            int shutdownMinute = int.Parse(Properties.Settings.Default.ShutDownTime.Split(':').Last());




            TimeSpan ShutDownTime = new TimeSpan(shutdownHour, shutdownMinute, 0);

            if (nowTime == ShutDownTime)
                ShutDown();



        }

        public void StartToRest(object sender, EventArgs e)
        {
            //TextBlock.Text = "00:00:02";
            TextBlock.Text = $"00:{Properties.Settings.Default.HintInterval.ToString().PadLeft(2, '0')}:00";

            FadeIn();

            dispatcherTimer.Start();
        }




        public void LockScreen()
        {
            dispatcherTimer.Stop();
            Window_LockScreen window_LockScreen = new Window_LockScreen();
            window_LockScreen.Show();
            FadeOut();
        }

        public void CountDown(object sender, EventArgs e)
        {
            int hour = int.Parse(TextBlock.Text.Split(':').First());
            int minute = int.Parse(TextBlock.Text.Split(':')[1]);
            int second = int.Parse(TextBlock.Text.Split(':').Last());

            TimeSpan timeSpan = new TimeSpan(hour, minute, second);
            timeSpan = timeSpan - new TimeSpan(0, 0, 1);



            if (timeSpan == new TimeSpan(0, 0, 0))
            {
                dispatcherTimer.Stop();
                TextBlock.Text = $"00:{Properties.Settings.Default.HintInterval.ToString().PadLeft(2, '0')}:00";
                //TextBlock.Text = $"00:00:02";
                if (Shutdown && Properties.Settings.Default.ShutDown)
                {
                    this.Close();
                    try
                    {
                        Process.Start(@"C:\Windows\System32\shutdown.exe", "-s -t 1");//关机
                        Console.WriteLine("执行关机命令");
                    }
                    catch (Exception ex) { MessageBox.Show(ex.Message); }
                }
                else
                {
                    LockScreen();
                }


            }



            TextBlock.Text = $"{timeSpan.Hours.ToString().PadLeft(2, '0')}:{timeSpan.Minutes.ToString().PadLeft(2, '0')}:{timeSpan.Seconds.ToString().PadLeft(2, '0')}";


        }


        public async void FadeIn()
        {
            this.Visibility = Visibility.Hidden;
            this.Opacity = 0;
            double opacity = this.Opacity;
            await Task.Run(() =>
            {
                while (opacity < 1)
                {
                    this.Dispatcher.Invoke((Action)delegate { this.Opacity += 0.02; opacity = this.Opacity; });
                    Task.Delay(1).Wait();
                }
            });
            this.Visibility = Visibility.Visible;
            this.Opacity = 1;
        }

        public async void FadeOut()
        {
            this.Opacity = 1;
            double opacity = this.Opacity;
            await Task.Run(() =>
            {
                while (opacity > 0)
                {
                    this.Dispatcher.Invoke((Action)delegate { this.Opacity -= 0.1; opacity = this.Opacity; });
                    Task.Delay(1).Wait();
                }
            });
            this.Visibility = Visibility.Hidden;
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
    }

    public static class GetWindow
    {
        public static Window Get(string name)
        {
            foreach (Window window in App.Current.Windows)
            {
                if (window.GetType().Name.ToUpper() == name.ToUpper()) return window;
            }
            return null;
        }
    }
}
